<?php
class PushAction extends Action{
/*
 * author zhanghao
 * */
	private $passphrase = '1234';	//pem keywords

/*
 * @name
 * 向服务器端注册设备devicetoken
 *
 * @arg
 * cid        int          企业id
 * uid        int          用户id
 * mobiletype int          1=ios 2=android
 * app_for    varchar      当前用户使用的功能
 * version    varchar      当前版本号
 *
 * @update
 * 2014-12-8 14:46 zhanghao
 * */
    public function reg_devicetoken(){
        if(!Database($_REQUEST["cid"]))exit;
        $_REQUEST["uid"]		=check_null(40002,true,$_REQUEST["uid"]);
        $_REQUEST["mobiletype"] =check_null(40064,true,$_REQUEST["mobiletype"]);
        $_REQUEST["devicetoken"]=check_null(40018,true,$_REQUEST["devicetoken"]);
        $_REQUEST["app_for"] 	=check_null(40065,true,$_REQUEST["app_for"]);
        $_REQUEST["version"] 	=check_null(40066,true,$_REQUEST["version"]);
        $_REQUEST['timestamp']  =time();
        if($_REQUEST['devicetoken']=='(null)'){return_json(40018);return;}

        $rs=D('Push')->add_devicetoken($_REQUEST);

        if($rs){
            return_json(0);
        }else{
            return_json(-1);
        }
    }

    public function push_many($title,$content,$keywords){
        //push init
        $post_data['push_key_words'] = $keywords;
        $post_data['message']        = "【".$title."】".$content;
        $post_data['message']        = mb_substr($post_data['message'],0,30);
        $post_data['message']        = nl2br($post_data['message']);
        $post_data['message']        = strip_tags( $post_data['message']);

        $tokens = D('Uri')->get_devicetokens($keywords);

        foreach($tokens as $val){
            if($val['mobiletype'] == 1){
                $post_data['tokens'][] = array(
                    'token' => $val['devicetoken'],
                    'badge' => (int)$val['badge'] + 1
                );
                $arr['app_for'] = 'home';
                $arr['uid']     = $val['uid'];
                D('Push')->update_badge_number(((int)$val['badge'] + 1),$arr);
            }
        }

        $this->push_more($post_data);
    }
/*
 * @name
 * 单人推送
 *
 * @arg
 * $data=array(
 *      uid     int     推送给谁
 *      app_for varchar 当前应用
 *      title   varchar 标题
 *      content varchar 消息内容
 *      sound   varchar 声音
 * )
 *
 * @update
 * zhanghao 2014/12/8 15:24
 * */
    public function push_one($data){
        if(!Database($data["cid"]))exit;
        $re	                = D('Push')->get_data_by_uid($data['uid'],$data['app_for']);
        $push['message']	= "[".$data['title']."]".$data['content'];
        $push['devicetoken']= $re['devicetoken'];
        $push['badge']      = (int)$re['badge'] + 1;
        $push['sound']      = $data['sound']!=''?$data['sound']:'default';
        $push['app_for']    = $data['app_for'];

        D('Push')->update_badge_number($push['badge'],$data);

        if($this->push_ios($push)){
            return true;
        }else{
            return false;
        }
    }

    public function push_ios($push){
        $body = array(
            "aps" => array(
                "category"          => "alert",
                'content-available' => 1,
                "alert"             => $push['message'],
                "badge"             => $push['badge'],
                "sound"             => $push['sound']
            )
        );
        $ck_path = 'Public/Core/Pems/'.$push['app_for'].'_ck.pem';

        $ctx = stream_context_create();
        stream_context_set_option($ctx,"ssl","local_cert",$ck_path);
        stream_context_set_option($ctx, 'ssl', 'passphrase', $this->passphrase);

        $fp = stream_socket_client("ssl://gateway.push.apple.com:2195", $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
        if (!$fp) {
            return false;
        }
        $payload = json_encode($body);
        $msg = chr(0) . pack("n",32) . pack("H*", str_replace(' ', '', $push['devicetoken'])) . pack("n",strlen($payload)) . $payload;
        fwrite($fp, $msg);
        fclose($fp);
        return true;
    }

/*
 * @name
 * 修改推送小红点
 *
 * @arg
 * uid          用户ID
 * devicetoken  设备ID
 * app_for      当前应用功能
 *
 * @update
 * 2014/12/8 16:44 zhanghao
 * */
    public function update_push_badge(){
        if(!Database($_GET["cid"]))exit;
        $_GET["uid"]			=check_null(40002,true,$_GET["uid"]);
        $_GET["devicetoken"] 	=check_null(40018,true,$_GET["devicetoken"]);
        $_GET["app_for"] 		=check_null(40065,true,$_GET["app_for"]);
        $_GET['last_open_time'] =time();
        $_GET['badge']			=0;

        $rs=D('Push')->init_badge($_GET);
        if($rs){
            return_json(0);
        }else{
            return_json(-1);
        }
    }



//test function
    public function push_test(){
        $push['message']	= '您有一条新的消息';
        $push['devicetoken']= 'dab9cc1bcd32487727652b4444e2a2d167fdb44356aaf4b2fd9db160554cbc68';
        $push['sound']      = 'default';
        $push['app_for']    = 'home';
        $push['badge']      = 1;

        if($this->push_ios($push)){
            dump(1);
            return true;
        }else{
            dump(0);
            return false;
        }
    }

    public function push_more($post_data){
        $post_data=json_encode($post_data);
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,"http://115.29.41.83/Public/apnsphp/sample_push_many.php");
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, array('json'=>$post_data));
        $rs = curl_exec($ch);
        curl_close($ch);
    }

    public function get_uris(){

        //数据初始化
        switch(''){
            case $_POST['message']:$this->no_error(-1,"no message");return;
            case $_POST['mobiletype']:$this->no_error(-1,"no type");return;
        }
        $timestamp	=time();
        $data['title']		=$_POST['title'];
        $data['towho']		=$_POST['sel'];
        $data['message']   	=$_POST["message"];
        $data['mobiletype']	=$_POST["mobiletype"];
        $data['sort']		=(int)$_POST['sort'];
        if (preg_replace('/[\n\r\t]/','',preg_replace('/\s(?=\s)/','',trim($data['message'])))==''){
            $this->no_error(-1,"uncorrct message");
            return;
        }
        $data['time_insert']=$timestamp;
        $data['time_update']=$timestamp;
        $data['time_delete']=-1;
        $data['title']=$_POST['title'];

        //添加
        if(!M('push_message','','DB_MEETING')->add($data)){
            $this->no_error(-2,"Add message fail");
            return;
        }
        add_time_center('push');

        //获取需要推送的设备号
        $sql['uri']="select * from uri where 1=1";
        switch($data['mobiletype']){
            case 'IOS':$sql['uri'].=" and mobiletype='IOS'";break;
            case 'ANDROID':$sql['uri'].=" and mobiletype='ANDROID'";break;
        }
        if($data['towho']>0)
            $sql['uri'].=" and group_id={$data['towho']}";
        $uris=M('uri','','DB_MEETING')->query($sql['uri']);
        if(!$uris){
            $this->no_error(-3,'find no device');
            return;
        }

        //信息推送
        //init 推送信息
        $push['message']="[".$data['title']."]".$data['message'];
        if(mb_strlen($push['message'])>60)
            $push['message']=mb_substr($push['message'],0,30,'UTF-8')."......";
        //init 声音
        $push['sound'] = 'default';
        //init 成功条数
        $right = 0;
        foreach($uris as $val){
            //init devicetoken
            $push['devicetoken']=$val['devicetoken'];
            if($val['mobiletype'] == "IOS"){
                //init badge
                $cond["devicetoken"] = $val['devicetoken'];
                $timestamp = (int)(M("uri","",'DB_MEETING')->where($cond)->getField("timestamp"));
                $push['badge']=M("push_message","",'DB_MEETING')->where("mobiletype!='ANDROID' and time_insert >= {$timestamp}")->count();

                $re=$this->IOS_pushmsg($push);
                if($re)
                    $right++;
            }
            if($val['mobiletype'] == "ANDROID"){
                $re=$this->ANDROID_pushmsg($push);
                if($re)
                    $right++;
            }
        }
        $this->no_error(1,"sucess number: ".$right."/".count($uris));
    }

}
?>